package cn.rukbat.demo3.controller;

import cn.rukbat.demo3.util.PasswordlessTokenUtil;
import cn.rukbat.demo3.util.SecureUrlBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Controller
public class ResourceController {
    
    @Autowired
    private SecureUrlBuilder secureUrlBuilder;
    
    @Autowired
    private PasswordlessTokenUtil tokenUtil;
    
    /**
     * 主页 - 展示免密码安全资源
     */
    @GetMapping("/")
    public String home(Model model) {
        // 构建免密码安全资源URL
        String secureCssUrl = secureUrlBuilder.buildSecureResourceUrl("/protected/css/style.css");
        String secureJsUrl = secureUrlBuilder.buildSecureResourceUrl("/protected/js/app.js");
        String secureImageUrl = secureUrlBuilder.buildSecureResourceUrl("/protected/images/logo.png");
        
        model.addAttribute("secureCssUrl", secureCssUrl);
        model.addAttribute("secureJsUrl", secureJsUrl);
        model.addAttribute("secureImageUrl", secureImageUrl);
        model.addAttribute("currentTime", System.currentTimeMillis());
        model.addAttribute("tokenExpiry", tokenUtil.getTokenExpirySeconds());
        
        return "index";
    }
    
    /**
     * 生成安全URL的API（内部使用）
     */
    @PostMapping("/api/generate-secure-url")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> generateSecureUrl(@RequestBody UrlRequest request) {
        String secureUrl = secureUrlBuilder.buildSecureResourceUrl(request.getResourcePath());
        
        Map<String, Object> response = new HashMap<>();
        response.put("secureUrl", secureUrl);
        response.put("resourcePath", request.getResourcePath());
        response.put("timestamp", System.currentTimeMillis());
        response.put("expiresIn", tokenUtil.getTokenExpirySeconds());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 使用预共享密钥生成安全URL（外部系统调用）
     */
    @PostMapping("/api/generate-secure-url/psk")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> generateSecureUrlWithPSK(@RequestBody PskUrlRequest request) {
        String clientId = request.getClientId() != null ? request.getClientId() : tokenUtil.generateClientId();
        String secureUrl = secureUrlBuilder.buildSecureResourceUrlWithPSK(request.getResourcePath(), clientId);
        
        Map<String, Object> response = new HashMap<>();
        response.put("secureUrl", secureUrl);
        response.put("resourcePath", request.getResourcePath());
        response.put("clientId", clientId);
        response.put("timestamp", System.currentTimeMillis());
        response.put("expiresIn", tokenUtil.getTokenExpirySeconds());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 批量生成安全URL
     */
    @PostMapping("/api/generate-batch-urls")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> generateBatchUrls(@RequestBody BatchUrlRequest request) {
        String baseUrl = request.getBaseUrl();
        String[] resourcePaths = request.getResourcePaths();
        
        String secureUrls = secureUrlBuilder.buildBatchSecureUrls(baseUrl, resourcePaths);
        
        Map<String, Object> response = new HashMap<>();
        response.put("secureUrls", secureUrls);
        response.put("count", resourcePaths.length);
        response.put("timestamp", System.currentTimeMillis());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 验证Token API
     */
    @GetMapping("/api/validate-token")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> validateToken(
            @RequestParam String token,
            @RequestParam String resourcePath,
            @RequestParam Long timestamp,
            @RequestParam(required = false) String clientId) {
        
        boolean isValid;
        
        if (clientId != null) {
            isValid = tokenUtil.validateTokenWithPSK(token, resourcePath, timestamp, clientId);
        } else {
            isValid = tokenUtil.validateToken(token, resourcePath, timestamp);
        }
        
        boolean isTimestampValid = tokenUtil.isTimestampValid(timestamp);
        
        Map<String, Object> response = new HashMap<>();
        response.put("valid", isValid);
        response.put("timestampValid", isTimestampValid);
        response.put("resourcePath", resourcePath);
        response.put("timestamp", timestamp);
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 文件下载页面
     */
    @GetMapping("/downloads")
    public String downloads(Model model) {
        // 在实际应用中，可以从数据库或配置中获取可下载资源列表
        String[] downloadResources = {
            "/protected/downloads/document.pdf",
            "/protected/downloads/report.xlsx", 
            "/protected/downloads/manual.docx"
        };
        
        model.addAttribute("downloadResources", downloadResources);
        return "downloads";
    }
    
    // 请求对象定义
    public static class UrlRequest {
        private String resourcePath;
        
        public String getResourcePath() {
            return resourcePath;
        }
        
        public void setResourcePath(String resourcePath) {
            this.resourcePath = resourcePath;
        }
    }
    
    public static class PskUrlRequest {
        private String resourcePath;
        private String clientId;
        
        public String getResourcePath() {
            return resourcePath;
        }
        
        public void setResourcePath(String resourcePath) {
            this.resourcePath = resourcePath;
        }
        
        public String getClientId() {
            return clientId;
        }
        
        public void setClientId(String clientId) {
            this.clientId = clientId;
        }
    }
    
    public static class BatchUrlRequest {
        private String baseUrl;
        private String[] resourcePaths;
        
        public String getBaseUrl() {
            return baseUrl;
        }
        
        public void setBaseUrl(String baseUrl) {
            this.baseUrl = baseUrl;
        }
        
        public String[] getResourcePaths() {
            return resourcePaths;
        }
        
        public void setResourcePaths(String[] resourcePaths) {
            this.resourcePaths = resourcePaths;
        }
    }
}
